import { createRouter, createWebHistory } from 'vue-router'

// 确保所有组件正确导入
const HomeView = () => import('@/views/HomeView.vue') // 动态导入提升性能
const DiaryView = () => import('@/views/DiaryView.vue')
const DiaryDetail = () => import('@/views/DiaryDetail.vue')
const AboutView = () => import('@/views/AboutView.vue')
const NotFound = () => import('@/views/NotFound.vue')
const ProfileView = () => import('@/views/ProfileView.vue')

// const routes = [
//   { 
//     path: '/',
//     name: 'home',
//     component: HomeView
//   },
//   { 
//     path: '/diary',
//     name: 'diary-list', // 更明确的命名
//     component: DiaryView
//   },
//   {  
//     path: '/diary/:id(\\d+)', // 只匹配数字ID
//   name: 'diary-detail',
//   component: DiaryDetail,
//   props: true
//   },
//   { 
//     path: '/about',
//     name: 'about',
//     component: AboutView
//   },
//   { 
//     path: '/', component: HomeView ,
//     path: '/profile', component: ProfileView 
//   },
//   { 
//     path: '/:catchAll(.*)', // 更标准的404路径匹配
//     component: NotFound
//   }
// ]
const routes = [
  { path: '/', name: 'home', component: HomeView },
  { path: '/diary', name: 'diary-list', component: DiaryView },
  { 
    path: '/diary/:id(\\d+)',  // ✅ 限制为数字ID
    name: 'diary-detail',
    component: DiaryDetail,
    props: true
  },
  { path: '/about', name: 'about', component: AboutView },
  { path: '/profile', name: 'profile', component: ProfileView }, // ✅ 独立路由
  { path: '/:catchAll(.*)', component: NotFound }
]

// const router = createRouter({
//   history: createWebHistory(),
//   routes,
//   scrollBehavior(to, from, savedPosition) { // 解决切换页面滚动位置问题
//     return savedPosition || { top: 0 }
//   }
// })
// 增加路由元信息和导航守卫
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 修复详情页跳转时滚动位置问题
    if (to.name === 'diary-detail') {
      return { top: 0, behavior: 'smooth' }
    }
    return savedPosition || { top: 0 }
  }
})

// 添加全局路由守卫
// router.beforeEach((to, from, next) => {
//   // 确保所有动态路由的组件完全卸载
//   if (from.matched.some(record => record.path === '/diary/:id(\\d+)')) {
//     const oldComponent = from.matched[0].instances.default
//     if (oldComponent) oldComponent.$destroy()
//   }
//   next()
// })
export default router